#include "bsp_adc.h"


void adc_config(void)
{
     /* enable ADC clock */
    rcu_periph_clock_enable(RCU_ADC);;
    /* config ADC clock */
    rcu_adc_clock_config(RCU_ADCCK_APB2_DIV6);
    
    /* ADC data alignment config */
    adc_data_alignment_config(ADC_DATAALIGN_RIGHT);
    /* ADC channel length config */
    adc_channel_length_config( ADC_REGULAR_CHANNEL, 1U);
    
    /* ADC trigger config */
    adc_external_trigger_source_config( ADC_REGULAR_CHANNEL, ADC_EXTTRIG_REGULAR_NONE); 
    /* ADC external trigger config */
    adc_external_trigger_config(ADC_REGULAR_CHANNEL, ENABLE);
	/*ADC temperature and Vrefint enable*/
	adc_tempsensor_vrefint_enable();
    /* enable ADC interface */
    adc_enable();
    vTaskDelay(1U);
    /* ADC calibration and reset calibration */
    adc_calibration_enable();
}


uint16_t adc_channel_sample(uint8_t channel)
{
    /* ADC regular channel config */
    adc_regular_channel_config(0U, channel, ADC_SAMPLETIME_239POINT5);
    /* ADC software trigger enable */
    adc_software_trigger_enable(ADC_REGULAR_CHANNEL);

    /* wait the end of conversion flag */
    while(!adc_flag_get(ADC_FLAG_EOC));
    /* clear the end of conversion flag */
    adc_flag_clear(ADC_FLAG_EOC);
    /* return regular channel sample value */
    return (adc_regular_data_read());
}


uint16_t get_bat_volt(void)
{
   uint16_t adc_samp_result = 0;
   float adc_volt = 0;
   
   uint16_t adc_Vref_samp_result = 0;
   adc_Vref_samp_result = adc_channel_sample(ADC_CHANNEL_17);
    
   adc_samp_result = adc_channel_sample(ADC_CHANNEL_8);//ADC_CHANNEL_8 ADC_CHANNEL_17

   adc_volt = (adc_samp_result * 3.3) / 4096.0;
   adc_volt *= 4.0;
 
   return (uint16_t)(adc_volt * 1000 + 40);
}

#define window_size 20            
uint16_t buffer[window_size] = {0}; 

/*********************** 滑动窗口滤波函数 ****************************/
uint16_t sliding_average_filter(uint16_t value,uint16_t* ptick)
{
	static	uint8_t data_num = 0;
	uint16_t output = 0;
	uint16_t temp = 0;
	uint8_t i,y;

	if (data_num < window_size) 
	{
		buffer[data_num++] = value;
		output = 0xff; 
	}
	else
	{
		*ptick = 0;
		//冒泡排序
		for(i = 0; i<(data_num-1); i++)
		{
			for(y =  (unsigned char)(i + 1) ; y < data_num; y++)
			{//5 4  8  3 9
				if( buffer[i] > buffer[y])
				{
					temp = buffer[i];
					buffer[i] = buffer[y];
					buffer[y] = temp;
				}	
			}
		}
		
        output = buffer[0];
        //for(i = 1;i< data_num -1;i++)
        //{
        //    output += buffer[i];
        //}

		//output /= data_num - 2;
		data_num = 0;
	}

	return output;
}

uint8_t bat_led_gear(uint16_t volt)
{
	uint8_t now_bat= 0; 

	if(volt == 0xff)
	{
		return 0xff;
	} 
	
	if(volt >= 3950)
	{
		now_bat = 3;
	}
	else if((volt >= 3830) && (volt < 3950))
	{
		now_bat = 2;
	}
	else if((volt >= 3600) && (volt < 3830))
	{
		now_bat = 1;
                
	}
	else
	{
		return 0x0f;
	}
	
	return now_bat;
}